import json
from pathlib import Path
from .user import User

class DataManager:
    def __init__(self):
        self.data_dir = Path('data/users')
        self.data_dir.mkdir(parents=True, exist_ok=True)
        
    def save_user(self, user):
        file_path = self.data_dir / f"{user.user_id}.json"
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(user.to_dict(), f, ensure_ascii=False, indent=4)
            
    def load_user(self, username, password):
        for file_path in self.data_dir.glob('*.json'):
            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
                if data['username'] == username:
                    user = User()
                    user.__dict__.update(data)
                    if user.verify_password(password):
                        return user
        return None
    
    def user_exists(self, username):
        for file_path in self.data_dir.glob('*.json'):
            with open(file_path, 'r', encoding='utf-8') as f:
                if json.load(f)['username'] == username:
                    return True
        return False 